package view.actionListeners;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import utils.PlayerSides;
import view.AddKingsPanel;
import view.AddPiecePanel;
import view.ChessGUI;
import controller.Controller;

/**
 * Class implements a listener for button to add to the board a King for each player
 */
public class AddKingsListener implements ActionListener {

	// members
	private Controller gameManager;
	private ChessGUI frameManager; 
	private AddKingsPanel kingsPanel;
	private AddPiecePanel piecePanel;
	
	// public methods
	
	/**
	 * Constructor- creates a new action listener
	 * @param gameManager- reference to game manager
	 * @param frameManager- reference to game display's frame manager
	 * @param kingsPanel- panel to add the Kings
	 * @param piecePanel- panel to add the other pieces
	 */
	public AddKingsListener(Controller gameManager, ChessGUI frameManager, AddKingsPanel kingsPanel, AddPiecePanel piecePanel) {
		
		// set members according to given value
		this.gameManager = gameManager;
		this.frameManager = frameManager;
		this.kingsPanel = kingsPanel;
		this.piecePanel = piecePanel;
	}
	
	/**
	 * Adds the Kings at selected positions.
	 * After Kings are added, removes the panel to add the Kings and replaces it with
	 * a panel to add the other pieces
	 */
	@Override
	public void actionPerformed(ActionEvent event) {
		
		// get both Kings positions
		Point firstKingPosition = new Point(kingsPanel.getFirstRowIndex(), kingsPanel.getFirstColIndex());
		Point secondKingPosition = new Point(kingsPanel.getSecondRowIndex(), kingsPanel.getSecondColIndex());
		
		// check if positions do not collide
		if (firstKingPosition.equals(secondKingPosition)) {
			// notify that positions collide 
			JOptionPane.showMessageDialog(null, "Cannot add the Kings at the same position!", "Position Conflict", JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		// add Kings at selected positions
		gameManager.addPiece(firstKingPosition, "King", PlayerSides.Sides.White);
		gameManager.addPiece(secondKingPosition, "King", PlayerSides.Sides.Black);
		
		// place Kings on board
		frameManager.updateButtonIcon("King", firstKingPosition, PlayerSides.Sides.White);
		frameManager.updateButtonIcon("King", secondKingPosition, PlayerSides.Sides.Black);
		
		// remove add-kings panel
		frameManager.removePanel(kingsPanel);
		
		// place add-pieces panel
		frameManager.addPanel(piecePanel);
	}
}